React 元件生命週期指的是元件從初始化到渲染完成,再到組件卸載的整個過程。整個生命週期大概可以分為初始化階段、更新階段以及卸載階段。目前 React 的生命週期有分為新舊版,舊版生命週期一般是指 16.3 以前常用,但現在官方已經不推薦使用的方法,未來在 17 版可能會移除,我們將會在這一篇裡面先做介紹。
新版的 React 生命週期我們可以對照下面官網提供的生命週期圖,Mounting 就是初始化階段、Updating 是更新階段、Unmounting 是卸載階段,這邊先做簡單的整理,下一篇會再用一些範例來解釋使用的方法。
constructor 構造函數,再執行 render 去渲染元件,完成元件渲染後再接著渲染 DOM 和 refs。在全部都完成後,會去執行 componentDidMount 這個方法,componentDidMount 是在元件整個渲染完畢後才會執行。props 有更新,或是執行 setState(),或者使用強制更新 forceUpdate()。當這幾種情形發生後,一樣會去執行渲染的工作,在渲染完畢後,會執行 componentDidUpdate。componentWillUnmount,是在卸載前會執行的事情。
getDerivedStateFromProps 是在 props 有變動、setState() 執行或是 forceUpdate() 執行的時候才會觸發執行,其實就是在資料更新的時候。但需要注意的是,它在初始化時候也會執行,在 constructor 建立後就會執行。shouldComponentUpdate 是接在 getDerivedStateFromProps 後面執行,默認返回 true,如果為 true 就會就會執行更新,false 則不會更新。getSnapshotBeforeUpdate 是在 render 執行後,DOM 和 refs 更新前所做的事情。舊版 React 生命週期方法有使用一些在新版已經不被建議使用的方法(在17版會刪除),但因為在專案開發上,有時候還是會遇到舊版的語法,因此還是在這邊簡單整理一下。這幾個方法包含 componentWillMount()、componentWillReceiveProps()、componentWillUpdate()。
componentWillMount() 在初始化階段執行,在 render 執行前,會先執行這個方法。在這裡可以做一些渲染前的預先處理行為,比方說預先請求資料。在新版 componentWillMount() 將會被改為 UNSAFE_componentWillMount()。componentWillReceiveProps(nextProps) 會在 props 改變時,於元件更新的階段做執行,它接受一個參數 nextProps,就是更新後最新的 props。class UserProfile extends React.Component {
state = {
name: 'leo',
age: 20
}
changeVlue (state) {
return new Promise((resolve) => {
this.setState(state, resolve)
})
}
async changeData () {
const { age } = this.state
await this.changeVlue({age: age + 1})
}
render () {
const { name, age } = this.state;
return <div>
{name} {age} 歲
<button onClick={this.changeData.bind(this)}>+1</button>
<Form age={age} />
</div>
}
}
每次父元件更新時,子元件都會得到最新的 nextProps
class Form extends React.Component {
state = {
value: null
}
componentWillReceiveProps (nextProps) {
console.log('componentWillReceiveProps', nextProps) // nextProps 會得到每次更新後最新的 props
this.setState({value: nextProps.age})
}
render () {
const { value } = this.state
return <div>
{value}
</div>
}
}
componentWillUpdate() 會在 render 方法之前執行,在新版已經被 getSnapshotBeforeUpdate() 取代。這個方法比較少被使用到,因此這邊就不多加介紹。這一篇先介紹了 React 舊版的生命週期方法,並簡易整理新版生命週期方法,下一篇我們會做比較詳細的整理。